<?php

namespace App\Http\Controllers\Api;


use App\Modules\Comment\Jobs\CheckJob;
use App\Modules\Comment\Models\Comment;
use App\Modules\Order\Models\CombinedOrder;
use App\Modules\Order\Models\Order;
use App\Modules\Payment\Models\WeChatPay;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class OrderController extends ApiController
{
    public function getList(Request $request)
    {
        $this->validate($request, [
            'offset' => 'integer',
            'count' => 'integer',
            'status' => 'nullable|string',
        ]);
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 10);
        $status = $request->input('status');
        $user = $this->getUser();
        $query = Order::query()
            ->where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->offset($offset)
            ->limit($count);
        switch ($status) {
            case "init":
                # 待支付
                $query->where('status', 'init');
                break;
            case "paid":
                # 已支付
                $query->where('status', 'paid')
                    ->where('is_prepay', 1)
                    ->where('is_finish', 0);
                break;
            case "received":
                # 待收货
                $query->where('status', 'paid')
                    ->where('final_payment', 1)
                    ->where('is_finish', 0);
                break;
            case "return":
                # 退换/售后
                $query->where('status', 'refund');
                break;
            case "evaluate":
                # 待评价
                $query->where('status', 'paid')
                    ->where('is_comment', 0)
                    ->where('is_finish', 1);
                break;
        }
        $re = $query->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'type' => $item->type,
                    'title' => $item->title,
                    'price' => $item->price,
                    'original_price' => $item->original_price,
                    'link_id' => $item->link_id,
                    'coupon_pay' => $item->coupon_pay,
                    'refund_fee' => $item->refund_fee,
                    'number' => $item->number,
                    'cover' => $item->cover,
                    'status' => $item->status,
                    'delivery' => $item->delivery,
                    'is_comment' => $item->is_comment,
                    'is_finish' => $item->is_finish,
                    'is_prepay' => $item->is_prepay,
                    'final_payment' => $item->final_payment,
                    'detail' => $item->detail,
                    'buyer_confirm' => $item->buyer_confirm,
                    'gift' => $item->gift,
                    'discount_amount' => $item->discount_amount,
                    'is_balance' => $item->is_balance,
                    'balance_pay' => $item->balance_pay,
                ];
            });
        return $this->success($re);
    }

    public function getDetail(Request $request)
    {
        $this->validate($request, [
            'id' => "required|integer",
        ]);
        $id = $request->input('id');
        $user = $this->getUser();
        $order = Order::query()
            ->where('id', $id)
            ->where('user_id', $user->id)
            ->first();
        return $this->success($order);
    }

    // 订单详情接口
    public function getOrderDetail(Request $request)
    {
        $this->validate($request, [
            'id' => "required|integer",
        ]);
        $id = $request->input('id');
        $user = $this->getUser();
        $order = Order::query()
            ->where('id', $id)
            ->first();
        return $this->success($order);
    }

    public function getRecommend(Request $request)
    {
        $this->validate($request, [
            'user_id' => 'nullable|integer',
            'offset' => 'nullable|integer',
            'count' => 'nullable|integer',
            'search' => 'nullable|string',
        ]);
        $user = $this->getUser();
        $userId = $request->input('user_id');
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 10);
        $search = $request->input('search');

        $query = Order::query();
        if (!empty($userId)) {
            $tmp = User::query()->find($userId);
            if ($tmp->personal_id == $user->id) { //上级id=自己
                $userId = $tmp->id;
            } else {
                return $this->fail('没有权限查看');
            }

        } else {
            $userId = $user->id;
        }

        /**
         * 订单状态
         *
         * 待审核    type = init;    status = init
         * 待提现    type = issued;  status = issued
         * 提现中    type = ing;     status = finish && withdrawal_status = pending
         * 累计提现  type = total;   withdrawal_status = success
         */
        $type = strip_tags($request->input('type'));
        $aWhere = [];
        switch ($type) {
            case 'init':
                // 待审核
                $aWhere['rebates.status'] = 'init';
                break;

            case 'issued':
                // 待提现
                $aWhere['rebates.status'] = 'issued';
                break;

            case 'ing':
                // 提现中
                $aWhere['rebates.status'] = 'finish';
                $aWhere['rebates.withdrawal_status'] = 'pending';
                break;

            case 'total':
                // 累计提现
                $aWhere['rebates.withdrawal_status'] = 'success';
                break;

            default:
                break;
        }

        /**
         * 订单创建时间查询
         */
        $time = strip_tags($request->input('time'));

        // $time = '2020-06-21~2020-06-30';
        if ($time && $time != 'null~null') {
            $time = explode('~', $time);
            $stime = $time[0] . ' 00:00:00';
            $etime = $time[1] . ' 23:59:59';
            $aWhere[] = ['orders.created_at', '>', $stime];
            $aWhere[] = ['orders.created_at', '<', $etime];
        }
            
        $order = $query
                // ->leftJoin('users', 'users.id', '=', 'orders.referrer_id')
                // ->leftJoin('users', 'users.id', '=', 'orders.user_id')
                ->leftJoin('rebates', 'orders.id', '=', 'rebates.link_id')
                ->where('orders.referrer_id', $userId)
                ->when(!empty($search), function ($query) use ($search) {
                    return $query->where(function ($query) use ($search) {
                        return $query->where('orders.name', 'like', "%".$search."%")
                            ->orWhere('orders.mobile', 'like', "%".$search."%")
                            ->orWhere('orders.id', $search);
                            // ->orWhere('re.status', 'issued');
                    });
                })
                ->where($aWhere)
                ->orderBy('orders.created_at', 'desc')
                ->offset($offset)
                ->limit($count)
                ->get(['orders.*']);
        $users = User::query()->whereIn('id', $order->pluck('user_id')->all())->get()->keyBy('id');
        $shops = Shop::query()->whereIn('id', $order->pluck('shop_id')->all())->get()->keyBy('id');

        $rebates = Rebate::query()
            ->where('origin', Order::class)
            ->whereIn('link_id', $order->pluck('id')->all())
            ->get()
            ->keyBy('link_id');

        $re = $order->map(function ($item) use ($users, $shops, $rebates) {
            $user = $users->get($item->user_id);
            $shop = $shops->get($item->shop_id);
            $rebateStatus = null;
            $rebate = $rebates->get($item->id);
            if (!is_null($rebate)) {
                if ($rebate->status == Rebate::STATUS_FINISH) {
                    $rebateStatus = Rebate::$withdrawalStatusShow[$rebate->withdrawal_status];
                } else {
                    $rebateStatus = Rebate::$statusShow[$rebate->status];
                }
            }
            return [
                'id' => $item->id,
                'user_id' => $item->user_id,
                'nickname' => $user->nickname ?? '',
                'type' => $item->type,
                'cover' => $item->cover,
                'title' => $item->title,
                'link_id' => $item->link_id,
                'number' => $item->number,
                'coupon_pay' => $item->coupon_pay,
                'refund_fee' => $item->refund_fee,
                'price' => $item->price,
                'original_price' => $item->original_price,
                'referrer_id' => $item->referrer_id,
                'referrer_level' => $item->referrer_level,
                'status' => $item->status,
                'is_finish' => $item->is_finish,
                'delivery' => $item->delivery,
                'is_comment' => $item->is_comment,
                'detail' => $item->detail,
                'created_at' => $item->created_at,
                'mobile' => $item->mobile,
                'name' => $item->name ?? '',
                'gift' => $item->gift,
                'shop' => $shop->name ?? '',
                'buyer_confirm' => $item->buyer_confirm,
                'is_prepay' => $item->is_prepay,
                'final_payment' => $item->final_payment,
                'rebate_status' => $rebateStatus,
                'discount_amount' => $item->discount_amount,
            ];
        });
        return $this->success($re);
    }

    public function cancel(Request $request)
    {
        $this->validate($request, [
            'id' => "required|integer",
        ]);
        $id = $request->input('id');
        $user = $this->getUser();
        Order::query()
            ->where('id', $id)
            ->where('user_id', $user->id)
            ->where('status', Order::STATUS_INIT)
            ->first()
            ->close();
        return $this->success();
    }

    public function getStatus(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $order = Order::query()
            ->where('id', $id)
            ->first();
        if (is_null($order)) {
            return $this->fail('订单id错误');
        }
        return $this->success($order->status);
    }

    public function getCombinedOrderStatus(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $order = CombinedOrder::query()
            ->where('id', $id)
            ->first();
        if (is_null($order)) {
            return $this->fail('订单id错误');
        }
        return $this->success($order->status);
    }

    public function getCombinedOrderDetail(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $user = $this->getUser();

        $order = CombinedOrder::query()
            ->where('id', $id)
            ->where('user_id', $user->id)
            ->first();
        return $this->success($order);
    }

    public function comment(Request $request)
    {
        $this->validate($request, [
            'order_id' => 'required|integer',
            'id' => 'required|integer',
            'score' => 'required|integer',
            'content' => 'nullable|string',
            'image' => 'nullable|array',
        ]);
        $user = $this->getUser();
        $orderId = $request->input('order_id');
        $id = $request->input('id');
        $content = $request->input('content');
        $image = $request->input('image');
        $score = $request->input('score');

        if (!empty($content)) {
            $app = EasyWeChat::miniProgram();
            $result = $app->content_security->checkText($content);
            if ($result['errcode'] != 0) {
                return $this->fail("发布内容包含敏感词");
            }
        }

        $order = Order::query()
            ->where('id', $orderId)
            ->where('user_id', $user->id)
            ->where('status', Order::STATUS_PAID)
            ->first();
        if (is_null($order)) {
            return $this->fail('未购买不能评价');
        }

        
        $comment = Comment::query()
            ->create([
                'user_id' => $user->id,
                'link_id' => $id,
                'score' => $score,
                'type' => $order->type == "good" ? "good" : "package",
                'content' => $content,
                'image' => $image,
                'is_checked' => 0,
                'is_show' => 0,
                'shop_id' => $order->shop_id,
                'order_id' => $orderId,
            ]);
        dispatch(new CheckJob($comment));
        if ($order->type == Order::TYPE_PACKAGE) {
            $order->is_comment = 1;
        } elseif ($order->type == Order::TYPE_GOOD) {
            $isComment = 1;
            $tmp = [];
            foreach ($order->detail as $value) {
                if ($value['good_id'] == $id) {
                    $value['is_comment'] = 1;
                }
                $isComment = $value['is_comment'] ?? 0;
                $tmp[] = $value;
            }
            $order->is_comment = $isComment;
            $order->detail = $tmp;
        }
        $order->save();
        return $this->success();
    }

    public function finish(Request $request)
    {
        $this->validate($request, [
            'id' => "required|integer",
        ]);
        $id = $request->input('id');
        $user = $this->getUser();
        $order = Order::query()
            ->where('id', $id)
            ->where('user_id', $user->id)
//            ->where('final_payment', 1)
//            ->where('is_finish', 1)
            ->where('status', Order::STATUS_PAID)
            ->first();
        $order->update([
            'buyer_confirm' => 1,//买家确认
        ]);
        $order->finish("userOperation");

        return $this->success();
    }

    public function getPayParam(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
        ]);
        $id = $request->input('id');
        $user = $this->getUser();
        /** @var Order $order */
        $order = Order::query()
            ->where('user_id', $user->id)
            ->where('id', $id)
            ->where('status', Order::STATUS_INIT)
            ->first();
        if (is_null($order)) {
            return $this->fail('订单异常');
        }
        $weChatPay = WeChatPay::query()
            ->where('out_trade_no', $order->pay_no)
            ->first();
        if (is_null($weChatPay)) {
            if ($order->getPrice() > 0) {
                $params = WeChatPay::getParameters($order->getType(), $order->pay_no, $order->title, $order->getPrice(), $user);
            } else {
                $params = null;
            }
        } else {
            $payment = EasyWeChat::payment();
            $params = $payment->jssdk->sdkConfig($weChatPay->prepay_id);
        }
        return $this->success($params);
    }

    /**
     * xiaoyu - back键之后发送模板消息
     * 参数：订单ID,模板ID
     * 管理端提示-到店自取-定金支付-会员下单后未支付退出提示 -36
     * 管理端提示-到店自取-全款支付-会员下单后未支付退出提示 -37
     * 管理端提示-物流发货-定金支付-会员下单后未支付退出提示 -38
     * 管理端提示-物流发货-全款支付-会员下单后未支付退出提示 -39
     * @param Request $request
     */
    public function checkBackSendMsg(Request $request)
    {
        $this->validate($request, [
            'id' => 'required|integer',
            "template_id" => "required|integer"
        ]);
        $id = $request->input('id');
        $template_id = $request->input('template_id');

        $user = $this->getUser();
        $user = User::query()->where("id", $user->id)->first();
        $order = Order::query()
            ->where('id', $id)
            ->first();
        $systemUser = User::query()
            ->whereRaw("JSON_CONTAINS(shop_id, '\"" . $order->shop_id . "\"')")
            ->where("is_palm_management", 1)
            ->get(["openid","is_palm_management"])->toArray();
        $sendData = [$user->openid, $id, date("Y年m月d日 H时i分s秒"), $order->title];
        sendSystem($systemUser,$template_id, $sendData);
        return $this->success();
    }
}
